package util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Create by 游德禄 on 2019-9-9
 * 日期处理工具
 */
public class DateUtil {
    /**
     * 把日期转换转指定格式的字符串
     * @param date
     * @param fmt
     * @return
     */
    public static String format(Date date,String fmt){
        return format(date,fmt,null);
    }
    public static String format(Date date,String fmt,String tip){
        if(date==null){
            if(tip!=null){
                return tip;
            }
            return "未选择";
        }
        if(fmt==null){
            fmt = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(fmt) ;
        String time = dateFormat.format(date);
        return time;
    }

    /**
     * 把一个字符转换成对应的日期
     * @param d
     * @param fmt
     * @return
     */
    public static Date parse(String d,String fmt){
        if(fmt==null){
            fmt = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(fmt) ;
        Date date = null;
        try {
            date = dateFormat.parse(d);
        }catch (Exception e){
        }
        return date;
    }

    public static int getCurrentMonthLastDay() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    public static String getCurrentYearAndMonth(){
        Calendar a = Calendar.getInstance();
        int year = a.get(Calendar.YEAR);
        int month = a.get(Calendar.MONTH) + 1;
        return year+"年"+month+"月";
    }

    public static int getFirstDayOfMonth(){
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DAY_OF_MONTH,1);
        int i = a.get(Calendar.DAY_OF_WEEK);
        return i;
    }
}
